<template>
    <div class="console"  v-loading="loading" >
        <div class="console-tools">
            <div class="console-tools-item">
                <el-button text  @click="saveQueryScript">
                    <el-icon size="16"><Document /></el-icon>
                    保存
                </el-button>
            </div>
            <div class="console-tools-item">
                <el-button  text @click="runConsoleScript">
                    <el-icon size="16"><View /></el-icon>
                    预览
                </el-button>
            </div>
            <div class="console-tools-item">
                <el-button  text @click="runConsoleScript(1)">
                    <Icon icon="ph:tree-structure" width="16"/>
                    解释
                </el-button>
            </div>
            <div class="console-tools-item">
                <el-button  text @click="formatConsoleInput">
                    <el-icon size="16"><MagicStick /></el-icon>
                    美化
                </el-button>
            </div>
        </div>
        <div class="console-tabs">
            <el-tabs type="border-card" v-model="defaultTab" @tab-change="changeTabs">
                <el-tab-pane label="定义" name="define">
                    <div class="console-edit"  :style="showType===1||showType===2?'height:calc(99vh - (99vh * 0.5) - 220px);':'height: calc(99vh - 220px);'">
                        <AceEditor  @getEditorInstance="getEditorInstance"/>
                    </div>
                    <div class="console-data" v-if="showType===1">
                        <div class="console-data-tips">
                            <div>只读</div>
                            <div>查询结果共计{{tableData.length}}条记录</div>
                        </div>
                        <el-table :data="tableData" border height="calc(99vh * 0.45)" highlight-current-row  @row-click="tableClickRow">
                            <el-table-column type="index" width="50" fixed >
                                <template #default="scope">
                                    <div style="width: 100%;display: flex;justify-content: flex-start;">
                                        <div v-if="selectRowIndex===(scope.$index+1)"><el-icon size="18"><CaretRight /></el-icon></div>
                                        <div>{{initIndex(scope.$index)}}</div>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column :key="field.COLUMN_NAME" :label="field.COLUMN_NAME"
                                             :min-width="getColumnWidth(field.COLUMN_NAME)" :prop="field.COLUMN_NAME" show-overflow-tooltip
                                             v-for="field in fieldData">
                                <template #default="scope">
                                    {{getDateFormat(field,scope.row[field.COLUMN_NAME])}}
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-tab-pane>
                <el-tab-pane label="高级" name="senior">
                    <el-form :model="seniorForm" label-width="auto" style="max-width: 600px">
                        <el-form-item label="算法">
                            <el-select v-model="seniorForm.ALGORITHM" >
                                <el-option label="UNDEFINED" value="UNDEFINED" />
                                <el-option label="MERGE" value="MERGE" />
                                <el-option label="TEMPTABLE" value="TEMPTABLE" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="作者">
                            <el-input v-model="seniorForm.DEFINER" />
                        </el-form-item>
                        <el-form-item label="安全性">
                            <el-select v-model="seniorForm.SECURITY_TYPE">
                                <el-option label="DEFINER" value="DEFINER" />
                                <el-option label="INVOKER" value="INVOKER" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="检查选项">
                            <el-select v-model="seniorForm.CHECK_OPTION" >
                                <el-option label="CASCADED" value="CASCADED" />
                                <el-option label="LOCAL" value="LOCAL" />
                            </el-select>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
                <el-tab-pane label="SQL预览" name="preview">
                    <div class="preview-box">{{previewSql}}</div>
                </el-tab-pane>
            </el-tabs>
        </div>
    </div>
</template>

<script setup name="MysqlTableQueryViewInfo">
    import AceEditor from '@/components/aceEditor'
    import {formatDate,formatTime} from "@/utils/dateUtils";
    import {format} from 'sql-formatter';
    const {proxy} = getCurrentInstance();
    const consoleData=reactive({
        showType:0,
        fieldData:[],
        tableData:[],
        tableCount: 0,
        loading:false,
        selectRowIndex:0,
        aceEditorInstance:null,
        formData:null,
        connectionInfo:null,
    })

    const {showType,fieldData,tableData,tableCount,loading,selectRowIndex,aceEditorInstance,formData,connectionInfo} =toRefs(consoleData)

    const tabData=reactive({
        defaultTab:'define',
        seniorForm:{},
        createView:null,
        previewSql:null,
    })
    const {defaultTab,seniorForm,createView,previewSql} =toRefs(tabData)


    function getEditorInstance(aceEditor) {
        aceEditorInstance.value = aceEditor
        if (seniorForm.value&&seniorForm.value.TABLE_NAME) {
            aceEditorInstance.value.session.setValue(seniorForm.value.VIEW_DEFINITION)
        }
    }

    function tableClickRow(row,column,event){
        selectRowIndex.value=(tableData.value.indexOf(row)+1)
    }

    function initParams() {
        let query= proxy.$route.query;
        if(Object.keys(query).length>0){
            let connect=proxy.$appStore.connectList.find(row=>row.id===(query.connectId*1))
            connect.database=query.databaseName
            connectionInfo.value=connect
            seniorForm.value=query
            if(seniorForm.value.TABLE_NAME){
                proxy.$userIpc.invoke(proxy.$ipcRouters.mysqlMng.runConsole, connectionInfo.value,{runScript:'SHOW CREATE VIEW `'+seniorForm.value.TABLE_NAME+'`'}).then(res=>{
                    createView.value=res.data.dataList[0]['Create View']
                })
            }
        }
    }


    watch(createView,(newVal,oldVal)=>{
        seniorForm.value.ALGORITHM=newVal.substring(newVal.indexOf('ALGORITHM=')+10,newVal.indexOf("DEFINER=")-1)
        seniorForm.value.DEFINER=newVal.substring(newVal.indexOf('DEFINER=')+8,newVal.indexOf("SQL ")-1)
    })

    function runConsoleScript(isExplain){
        if( aceEditorInstance.value.session.getValue().length<1){
            proxy.$modal.alertError("执行脚本不能为空")
            return
        }
        tableCount.value=0
        loading.value = true
        selectRowIndex.value=0
        let localParams={}
        if(isExplain===1){
            localParams.runScript="EXPLAIN   "+ aceEditorInstance.value.session.getValue()
        }else {
            localParams.runScript=aceEditorInstance.value.session.getValue()
        }
        proxy.$userIpc.invoke(proxy.$ipcRouters.mysqlMng.runConsole, connectionInfo.value,localParams).then(res=>{
            if(res.code===200){
                if(Array.isArray(res.data.dataList)){
                    showType.value=1//列表
                    tableData.value=res.data.dataList
                    fieldData.value=res.data.fieldList
                }else {
                    showType.value=2//结果
                }
            }else {
                proxy.$modal.alertError(res.message)
                loading.value = false
            }
        })
    }

    function formatConsoleInput() {
        aceEditorInstance.value.session.setValue(format(aceEditorInstance.value.session.getValue(), {language: 'mysql'}))
    }


    function getDateFormat(field,fieldValue){
        if(field.DATA_TYPE==='datetime'||field.DATA_TYPE==='timestamp'){
            return formatTime(fieldValue);
        }
        if(field.DATA_TYPE==='date'){
            return formatDate(fieldValue);
        }
        return fieldValue;
    }

    function initIndex(index) {
        let rowIndex = index + 1
        if(tableCount.value===0){
            loading.value = false
        }else if(rowIndex===tableCount.value){
            loading.value = false
        }
        return rowIndex;
    }

    function getColumnWidth(columnText) {
        if (columnText.length > 20) {
            return 180;
        }
        if (columnText.length > 10) {
            return 160;
        }
        if (columnText.length > 5) {
            return 120;
        }
        return 80;
    }

    function getScript(isUpdate,viewName) {
        let queryScript = aceEditorInstance.value.session.getValue()
        if(queryScript.length<1){
            return ''
        }
        let algorithm = ''
        if (seniorForm.value.ALGORITHM) {
            algorithm = `ALGORITHM = ${seniorForm.value.ALGORITHM}`
        }
        let security = ''
        if (seniorForm.value.SECURITY_TYPE) {
            security = `SQL SECURITY ${seniorForm.value.SECURITY_TYPE}`
        }
        let definer = ''
        if (seniorForm.value.DEFINER) {
            definer = `DEFINER = ${seniorForm.value.DEFINER}`
        }
        let checkOption = ''
        if (seniorForm.value.CHECK_OPTION&&seniorForm.value.CHECK_OPTION!=="NONE") {
            checkOption = `WITH ${seniorForm.value.CHECK_OPTION} CHECK OPTION`
        }

        let options = "CREATE "
        if (isUpdate===1) {
            options += "OR REPLACE "
        }
        return`${options} ${algorithm} ${definer} ${security} VIEW ${viewName} AS ${queryScript} ${checkOption}`
    }

    function saveQueryScript() {
        if( aceEditorInstance.value.session.getValue().length<1){
            proxy.$modal.alertError("执行脚本不能为空")
            return
        }
        if (seniorForm.value&&seniorForm.value.TABLE_NAME) {
            let viewName="`"+seniorForm.value.TABLE_SCHEMA+"`.`"+seniorForm.value.TABLE_NAME+"`"
            let params={}
            params.runScript=getScript(1,viewName);
            proxy.$userIpc.invoke(proxy.$ipcRouters.mysqlMng.runConsole, connectionInfo.value,params).then(res => {
                if(res.code===200){
                    proxy.$modal.msgSuccess("操作成功！");
                }else {
                    proxy.$modal.alertError(res.message)
                }
            })
        }else {
            proxy.$prompt('请输入视图名称', {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                closeOnClickModal: false,
                inputPattern: /\S/,
                inputErrorMessage: "视图名称不能为空",
            }).then(({value}) => {
                let viewName="`"+seniorForm.value.databaseName+"`.`"+value+"`"
                let params={}
                params.runScript=getScript(0,viewName);
                proxy.$userIpc.invoke(proxy.$ipcRouters.mysqlMng.runConsole, connectionInfo.value,params).then(res => {
                    if(res.code===200){
                        proxy.$modal.msgSuccess("操作成功！");
                    }else {
                        proxy.$modal.alertError(res.message)
                    }
                })
            }).catch(() => {
            });
        }
    }

    const handleEvent = async (event) => {
        if (event.keyCode === 83) {
            if (event.ctrlKey && event.code === 'KeyS') {
                event.preventDefault()
                event.returnValue = false;
                saveQueryScript()
            }
        }
    }

    onMounted(() => {
        window.addEventListener('keydown', handleEvent)
    });

    onUnmounted(() => {
        window.removeEventListener('keydown', handleEvent)
    });

    function changeTabs(){
        if(defaultTab.value==='preview'){
            if (seniorForm.value&&seniorForm.value.TABLE_NAME) {
                let viewName="`"+seniorForm.value.TABLE_SCHEMA+"`.`"+seniorForm.value.TABLE_NAME+"`"
                previewSql.value=getScript(1,viewName)
            }else {
                let viewName="`"+seniorForm.value.databaseName+"`.`Untitled`"
                previewSql.value=getScript(0,viewName)
            }
        }
    }
    initParams()
</script>
<style  lang="scss">
    .console{
        width: 100%;
        height: 99vh;
        user-select: text;
        &-tools{
            width: 100%;
            display: flex;
            justify-content: flex-start;
            border-bottom: 1px solid #DCDFE6;
            margin-left: 3px;
            &-item{
                border-left:  1px solid #DCDFE6
            }
        }

        &-data{
            width: 100%;
            &-tips{
                height: 24px;
                line-height: 24px;
                display: flex;
                justify-content: flex-start;
                font-size: 12px;
                div {
                    padding: 0 10px;
                    border-left: 1px solid #DCDFE6;
                    border-top: 1px solid #DCDFE6;
                }
            }
        }
    }
    .console-tabs{
        padding-left: 3px;
    }
    :deep(.el-table) {
        --el-table-row-hover-bg-color: transparent;
        --el-table-header-bg-color: transparent;
        --el-table-header-text-color: #303133;
    }

    :deep(.el-table thead th) {
        font-weight: normal;
    }
    .preview-box {
        width: 100%;
        height: calc(99vh - 220px);
        border-radius: 5px;
        border: 1px solid #D4D7DE;
        font-size: 12px;
        text-align: left;
        padding: 10px 0px 0px 10px;
    }

</style>
